<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminShayu\AdminRoleUser;
use App\Models\AdminShayu\AdminUser;
use App\Models\Orm\AwAuditRecord;
use App\Models\Orm\CooperativeCompany;
use App\Models\Orm\Product;
use App\Models\Orm\ProductAudit;
use App\Models\Orm\ProductLabels;
use App\Models\Orm\ProjectProduct;
use App\Models\Orm\Recommand;
use App\Models\Orm\Recommend;
use App\Models\Orm\SecondsKill;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

/**
 * 产品模块控制器
 *
 * Class ProductController
 * @package App\Http\Controllers\Admin
 */
class ShayuController extends Controller
{
    /**
     * 产品列表(展示页)
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $user = auth('admin')->user();

        // 所有认证通过的数据
        $data = CooperativeCompany::orderby('id', 'desc')->get()->toArray();

        // 处理account_type,用逗号分隔成数组
        foreach ($data as $key => $value) {
            $data[$key]['account_type'] = explode(',', $data[$key]['account_type']);
        }

        return view('admin.shayuhao.index', compact('data'));

    }

    /**
     * 新建产品审核
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        /**
         * 必须传商户类型
         * 必须传登录邮箱(在admin_users表唯一性)
         * 创建后台用户
         * 分配用户角色(多角色)
         * 创建合作方用户
         */

        if ($request->isMethod('post')) {
            // $request->flash();

            $data = $request->except(['_token', 'password', 'password_confirmation']);


            $password = '123qwe';

            $this->validate($request, [
                'short_name'   => 'required|string',
                'company_name' => 'required|string',
//				'legal_person' => 'required|string',
                // 手机号
//				'legal_phone'  => ['required', 'regex:/^1[34578]\d{9}$/'],
                // 密码(数字+字母,不能是纯数字或纯字母,6-10位)
                // 'password' => ['required', 'regex:/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/', 'min:6', 'max:10', 'confirmed'],
                // 确认密码,自动验证两次密码输入一致不一致
                // 'password_confirmation' => 'required|min:6|max:10',
                'account_type' => 'required|array',
                'login_email'  => 'required|email|unique:admin_users,email',
//				'logo'         => 'image|max:2048',
            ], [], [
                'short_name'   => '企业简称',
                'company_name' => '公司主体名称',
//				'legal_person' => '法人名称',
//				'legal_phone'  => '法人手机号',
                'account_type' => '商户类型',
                'login_email'  => '注册邮箱',
//				'logo'         => '公司LOGO',
            ]);


            $userData['email']      = $data['login_email'];
            $userData['name']       = substr(explode('@', $data['login_email'])[0], 0, 30);  // 最多截取30个字符
            $userData['password']   = bcrypt($password);
            $userData['created_at'] = $userData['updated_at'] = date('Y-m-d H:i:s');

//            DB::beginTransaction();

            // 创建后台用户
            $userId = AdminUser::insertGetId($userData);

            // 分配用户角色(多角色)
            $role_user['user_id'] = $userId;
            foreach ($data['account_type'] as $account_type) {
                if (in_array($account_type, array_keys(CooperativeCompany::$account_type_text))) {
                    $role_user['role_id'] = $account_type;
                    AdminRoleUser::create($role_user);
                }
            }

            // 创建合作方公司
            $data['is_auth']      = CooperativeCompany::IS_AUTH_ON;
            $data['user_id']      = $userId;
            $data['admin_id']     = auth()->user()->id;
            $data['handler']      = $userData['name'];
            $data['account_type'] = implode(',', $data['account_type']);
            $data['settled_time'] = $data['created_at'] = $data['updated_at'] = date('Y-m-d H:i:s');

            $integral = CooperativeCompany::insert($data);

//            if ($integral !== true) {
//                DB::rollback();
//                return redirect('/admin/anwenhao')->with(['error' => '添加失败']);
//            }
//            DB::commit();
            return redirect('/admin/shayuhao/index')->with(['info' => '添加成功']);
        }

        $data = new CooperativeCompany();
        return view('admin.shayuhao.create', compact('data'));
    }





    /**
     * 修改
     * @param Request $request
     * @return View
     */
    public function edit(Request $request)
    {
        $id     = $request->get('id');
        $data   = CooperativeCompany::find($id);


        return view('admin.shayuhao.edit', compact('data'));
    }




    /**
     * 修改提交
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request)
    {
        /**
         * 根据id查询合作方录入表记录,否则异常
         * 判断有没有更改登录邮箱,有则更admin_users表
         * 判断商户类型是不是有变化,有则更改admin_user_role表,少了则删除,多了则插入
         * 判断有没有上传图片logo
         */
        if ($request->isMethod('post')) {
            $data = $request->except(['_token', 'logo']);

            $id   = $data['id'];

            $cooperative_company = CooperativeCompany::find($id);

            if (!$cooperative_company) {
                return back()->with(['error' => '未找到数据']);
            }

            $user_id = $cooperative_company->user_id;


            DB::beginTransaction();

            $user = AdminUsers::find($user_id);
            // 判断有没有更改登录邮箱
            if ($data['login_email'] != $cooperative_company->login_email && !empty($user)) {
                $user->email = $data['login_email'];
                $result = $user->save();
                if ($result !== true) {
                    DB::rollback();
                    return back()->with(['error' => '登录邮箱更改失败'])->withInput($data);
                }
            }

            // 判断商户类型是不是有变化
            $old_account_type_array = explode(',', $cooperative_company->account_type);
            if ($data['account_type'] != $old_account_type_array) {
                // 清除旧角色
                $rows = AdminRoleUser::where('user_id', $user_id)->delete();
                if (!$rows) {
                    DB::rollback();
                    return back()->with(['error' => '用户角色修改失败'])->withInput($data);
                }

                // 添加新角色
                $role_user['user_id'] = $user_id;
                foreach ($data['account_type'] as $account_type) {
                    if (in_array($account_type, array_keys(CooperativeCompany::$account_type_text))) {
                        $role_user['role_id'] = $account_type;
                        AdminRoleUser::create($role_user);
                    }
                }

            }
            $data['account_type'] = implode(',', $data['account_type']);



            $data['admin_id'] = auth()->user()->id;
            $data['updated_at'] = date('Y-m-d H:i:s');

            $result = $cooperative_company->update($data);

            if ($result !== true) {
                DB::rollback();
                return back()->with(['error' => '公司信息更新失败'])->withInput($data);
            }

            DB::commit();
        }

        return redirect('/admin/shayuhao/index')->with(['info' => '修改成功']);

    }

}
